package Q707

class Main {

}

fun main(){

}


//双链表
internal class MyLinkedList {
    internal inner class ListNode(var `val`: Int) {
        var next: ListNode? = null
        var prev: ListNode? = null
    }

    var size = 0
    var head: ListNode
    var tail //Sentinel node
            : ListNode

    /** Get the value of the index-th node in the linked list. If the index is invalid, return -1.  */
    operator fun get(index: Int): Int {
        if (index < 0 || index >= size) {
            return -1
        }
        var cur: ListNode? = head

        // 通过判断 index < (size - 1) / 2 来决定是从头结点还是尾节点遍历，提高效率
        if (index < (size - 1) / 2) {
            for (i in 0..index) {
                cur = cur!!.next
            }
        } else {
            cur = tail
            for (i in 0..size - index - 1) {
                cur = cur!!.prev
            }
        }
        return cur!!.`val`
    }

    /** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.  */
    fun addAtHead(`val`: Int) {
        val cur = head
        val newNode: ListNode = ListNode(`val`)
        newNode.next = cur.next
        cur.next!!.prev = newNode
        cur.next = newNode
        newNode.prev = cur
        size++
    }

    /** Append a node of value val to the last element of the linked list.  */
    fun addAtTail(`val`: Int) {
        val cur = tail
        val newNode: ListNode = ListNode(`val`)
        newNode.next = tail
        newNode.prev = cur.prev
        cur.prev!!.next = newNode
        cur.prev = newNode
        size++
    }

    /** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.  */
    fun addAtIndex(index: Int, `val`: Int) {
        var index = index
        if (index > size) {
            return
        }
        if (index < 0) {
            index = 0
        }
        var cur: ListNode? = head
        for (i in 0 until index) {
            cur = cur!!.next
        }
        val newNode: ListNode = ListNode(`val`)
        newNode.next = cur!!.next
        cur.next!!.prev = newNode
        newNode.prev = cur
        cur.next = newNode
        size++
    }

    /** Delete the index-th node in the linked list, if the index is valid.  */
    fun deleteAtIndex(index: Int) {
        if (index >= size || index < 0) {
            return
        }
        var cur: ListNode? = head
        for (i in 0 until index) {
            cur = cur!!.next
        }
        cur!!.next!!.next!!.prev = cur
        cur.next = cur.next!!.next
        size--
    }

    /** Initialize your data structure here.  */
    init {
        head = ListNode(0)
        tail = ListNode(0)
        head.next = tail
        tail.prev = head
    }
}